<?php
/**
 * @file: rongyun_logm.php
 * @User: shiwuhao
 * @Date: 16/3/11 10:36
 * @synopsis:
 */

class Rongyun_logm extends CI_Model
{
    private $table = 'ml_rongyun_log';
    private $_version = '2.1.3';
    // im发送私信内容
    private $im_message = '亲爱的轻盈用户，您好：轻盈医学聊天功能已全面升级！您现在使用的版本不能与最新版本用户之间进行消息聊天。马上去应用商城下载新版轻盈医学，好友更多互动，体验全新群聊';
    // 官方帐号
    private $official_user_id = '31495';
    //private $official_user_id = '299543';
    // push信息
    private $push_message = '您的好友发送了聊天信息给你，请下载最新的版本查看';

    public function __construct()
    {
        parent::__construct();
        $this->load->model('imapim');
        $this->load->library('jpushmd');
    }

    /**
     * 更新融云log 
     * @param $user_id
     * @param $version
     */
    public function update_log($user_id, $version)
    {
        $filter = array('user_id' => $user_id, 'status' => 1);
        $log_info = $this->db->where($filter)->limit(1)->get($this->table)->row_array();

        $data = array('user_id' => $user_id, 'version'=>$version);
        if (version_compare($version, $this->_version) >= 0) { // 新版
            $data['is_new_version'] = 1;

            // 删除极光用户
            if ($user_id != $this->official_user_id) {
                $this->imapim->jg_del_member($user_id);
            }

        } else { // 旧版 每天发送一次私信消息 提示更新

            if (!$log_info || ($log_info && $log_info['send_im_time'] < strtotime(date('Y-m-d')))) {
                // 发送私信内容
                $this->imapim->jg_im_send_message($user_id, $this->im_message, $this->official_user_id);
                $data['send_im_time'] = time();
            }
        }

        if (!$log_info) {
            return $this->db->insert($this->table, $data);
        } else {
            return $this->db->update($this->table, $data, $filter);
        }
    }

    /**
     * 新版用户给旧版用户发送信息，旧版用户会收到push信息
     * @param $src_uid
     * @param $dest_uid
     */
    public function push($src_uid, $dest_uid)
    {
        $src_info  = $this->db->where(array('user_id' => $src_uid, 'status' => 1))->limit(1)->get($this->table)->row_array();
        $dest_info = $this->db->where(array('user_id' => $dest_uid, 'status' => 1))->limit(1)->get($this->table)->row_array();

        if (!$dest_info) { // 不存在，创建默认数据
            $data = array('user_id' => $dest_uid, 'version' => '2.1.1');
            $this->db->insert($this->table, $data);
            $dest_info = $this->db->where(array('user_id' => $dest_uid, 'status' => 1))->limit(1)->get($this->table)->row_array();
        }

        // 新版给旧版发送消息，旧版会收到一条 push信息
        if ( (version_compare($src_info['version'], $this->_version) >=0) && (version_compare($dest_info['version'], $this->_version) < 0) && ($dest_info['push_time'] < strtotime(date('Y-m-d'))) ) {
            $this->jpushmd->SendByAliasMore(array($dest_uid),$this->push_message,array('type' => 10));
            return $this->db->update($this->table, array('push_time' => time()), array('user_id' => $dest_uid));
        }
    }
}